package com.youpai.platform.vulture.common.entity;

import com.youpai.platform.vulture.common.enums.ClientCommandEnum;
import com.youpai.platform.vulture.common.enums.ServerCommandEnum;
import com.youpai.platform.vulture.common.util.AccessMessageSupport;
import org.apache.commons.collections4.CollectionUtils;

import java.util.List;

/**
 * @date: 2022/6/22 21:35
 * @author: Anna
 * @version: 1.0
 * @description: 自定义消息抽象类
 */
public class AccessMessage {

    /**
     * 消息标志 , 1 - 256
     * 不能为空
     * {@link com.youpai.platform.vulture.common.enums.MsgFlagEnum}
     */
    private int flag;

    /**
     * 头列表
     */
    private List<Header> headerList;

    /**
     * 消息体
     */
    private String body;

    public int getFlag() {
        return flag;
    }

    public AccessMessage setFlag(int flag) {
        this.flag = flag;
        return this;
    }

    public List<Header> getHeaderList() {
        return headerList;
    }

    public AccessMessage setHeaderList(List<Header> headerList) {
        this.headerList = headerList;
        return this;
    }

    public String getBody() {
        return body;
    }

    public AccessMessage setBody(String body) {
        this.body = body;
        return this;
    }

    public static AccessMessage build() {
        return new AccessMessage();
    }

    /**
     * 构造心跳消息
     *
     * @return 心跳消息
     */
    public static AccessMessage buildPingMessage() {
        return AccessMessageSupport.buildPingMessage();
    }

    /**
     * 构造心跳消息
     *
     * @return 心跳消息
     */
    public static AccessMessage buildPongMessage() {
        return AccessMessageSupport.buildPongMessage();
    }

    /**
     * 构造普通cmd消息
     *
     * @param clientCommandEnum 客户端命令
     * @param body body
     * @return 构造的消息
     */
    public static AccessMessage buildOrdinaryCmdMessage(ClientCommandEnum clientCommandEnum, String body) {
        return AccessMessageSupport.buildOrdinaryCmdMessage(clientCommandEnum, body);
    }

    /**
     * 构造普通命令消息
     *
     * @param serverCommandEnum 服务端命令
     * @param body 消息题
     * @return 消息
     */
    public static AccessMessage buildOrdinaryCmdMessage(ServerCommandEnum serverCommandEnum, String body) {
        return AccessMessageSupport.buildOrdinaryCmdMessage(serverCommandEnum, body);
    }

    @Override
    public String toString() {
        return "AccessMessage{" +
                "flag=" + flag +
                ", headerList=" + headerToString() +
                ", body='" + body + '\'' +
                '}';
    }

    private String headerToString() {
        if (CollectionUtils.isEmpty(headerList)) {
            return "";
        }
        StringBuilder result = new StringBuilder();
        for (Header header : headerList) {
            result.append(header.toString());
        }
        return result.toString();
    }
}

